package cn.zh.system.service.impl;

import cn.zh.base.query.BaseQuery;
import cn.zh.base.service.impl.BaseServiceImpl;
import cn.zh.base.util.PageList;
import cn.zh.system.domain.Menu;
import cn.zh.system.service.IMenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author zh
 * @since 2023-03-09
 */
@Service
public class MenuServiceImpl extends BaseServiceImpl<Menu> implements IMenuService {
    @Autowired
    private IMenuService service;

    @Override
    public List<Menu> first() {
        List<Menu> menus = service.findAll().stream().filter(menu -> menu.getParentId() == null && Objects.nonNull(menu)).collect(Collectors.toList());
        return menus;
    }

    @Override
    public List<Menu> tree() {
        ArrayList<Menu> list = new ArrayList<>();
        List<Menu> all = super.findAll();
        Map<Long, Menu> map = all.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        all.stream().forEach(menu -> {
            if (menu.getParentId() == null && Objects.nonNull(menu)) {
                list.add(menu);
            } else {
                Menu parent = map.get(menu.getParentId());
                parent.getChildren().add(menu);
            }
        });
        return list;
    }

    @Override
    public PageList<Menu> queryByPage(BaseQuery query) {
        PageList<Menu> list = super.queryByPage(query);
        List<Menu> rows = list.getRows();
        List<Menu> parents = rows.stream().filter(menu -> menu.getParentId() == null && Objects.nonNull(menu)).collect(Collectors.toList());
        Map<Long, Menu> map = parents.stream().collect(Collectors.toMap(Menu::getId, menu -> menu));
        rows.stream().forEach(menu -> {
            if (menu.getParentId() != null) {
                menu.setParent(map.get(menu.getParentId()));
            }
        });
        return list;
    }
}
